package com.redwine.app.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.redwine.app.APP;
import com.redwine.app.ApplyForSupplierActivity;
import com.redwine.app.ProcurementDetailActivity;
import com.redwine.app.R;
import com.redwine.app.chat.ChatActivity;
import com.redwine.app.chat.ChatConstant;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.CommonListDataResponse;
import com.redwine.app.net.responses.RedwineDetailResponse;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Settings;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.AlertDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品详情的适配器
 * 作者：gassion on 17/7/27 14:38
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class ProcurementAdapter extends BaseAdapter {

    private Context context;

    private String statusX;

    private List<RedwineDetailResponse.DataEntity.QuoteEntity> datalist;

    public ProcurementAdapter(Context context) {
        this.context = context;
    }


    /**
     * 设置数据
     *
     * @param datalist
     */
    public void setData(List<RedwineDetailResponse.DataEntity.QuoteEntity> datalist, String statusX) {
        this.datalist = datalist;
        this.statusX = statusX;
        notifyDataSetChanged();
    }

    public List<RedwineDetailResponse.DataEntity.QuoteEntity> getData() {
        if (null != datalist && !datalist.isEmpty()) {
            return datalist;
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public int getCount() {
        if (null != datalist) {
            return datalist.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        if (null != datalist) {
            return datalist.get(position);
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.activity_procurement_item, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final RedwineDetailResponse.DataEntity.QuoteEntity quoteEntity = datalist.get(position);
        BitmapUtils.loadImage(viewHolder.itemIvUserIcon, quoteEntity.getAvatar(), BitmapUtils.THE_ARTICLE);
        viewHolder.itemTvDate.setText(quoteEntity.getDate());
        viewHolder.itemTvUserName.setText(quoteEntity.getNickname());
        viewHolder.itemTvUserPhone.setText(quoteEntity.getMobile());

        if (!quoteEntity.getUid().equals(Global.user.getUid())) {
            if ("5".equals(statusX)) {
                viewHolder.itemTvSendMessage.setVisibility(View.INVISIBLE);
                viewHolder.itemTvAccept.setVisibility(View.INVISIBLE);
            } else {
                viewHolder.itemTvSendMessage.setVisibility(View.VISIBLE);
                viewHolder.itemTvAccept.setVisibility(View.VISIBLE);
                if ("2".equals(quoteEntity.getStatusX())) {
                    viewHolder.itemTvAccept.setText("取消采纳");
                } else {
                    viewHolder.itemTvAccept.setText("采纳");
                }
            }
            //viewHolder.itemTvDeleteQuoted.setVisibility(View.GONE);
        } else {
            //viewHolder.itemTvDeleteQuoted.setVisibility(View.VISIBLE);
            viewHolder.itemTvSendMessage.setVisibility(View.INVISIBLE);
            viewHolder.itemTvAccept.setVisibility(View.INVISIBLE);
        }

        if ("2".equals(quoteEntity.getStatusX())) {
            viewHolder.itemTvAcceptFlag.setVisibility(View.VISIBLE);
        } else {
            viewHolder.itemTvAcceptFlag.setVisibility(View.INVISIBLE);
        }

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {

                    case R.id.item_tv_delete_quoted:
                        //GASSION 删除报价
                        //Toast.makeText(context, "删除报价", Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.item_tv_send_message:
                        Intent intent = new Intent(context, ChatActivity.class);
                        intent.putExtra(ChatConstant.EXTRA_USER_ID, quoteEntity.getUid());//传递用户的唯一id
                        intent.putExtra(ChatConstant.EXTRA_USER_NICK_NAME, quoteEntity.getNickname());//传递用户的唯一id
                        intent.putExtra(ChatConstant.EXTRA_USER_AVATAR, quoteEntity.getAvatar());
                        context.startActivity(intent);
                        break;

                    case R.id.item_tv_accept:
                        final boolean isAdopt = "2".equals(quoteEntity.getStatusX());
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage(isAdopt ? "确认取消采纳该报价？" : "确认采纳该报价？");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (isAdopt) {
                                    //取消采纳
                                    requestCancelQuoteData(quoteEntity.getPublish_id(), quoteEntity.getUid());
                                } else {
                                    //请求采纳
                                    requestAdoptQuoteData(quoteEntity.getPublish_id(), quoteEntity.getUid());
                                }
                            }
                        });
                        AlertDialog mDialog = builder.create();
                        mDialog.setCancelable(false);
                        mDialog.show();
                        break;

                }
            }
        };

        //viewHolder.itemTvDeleteQuoted.setOnClickListener(onClickListener);
        viewHolder.itemTvSendMessage.setOnClickListener(onClickListener);
        viewHolder.itemTvAccept.setOnClickListener(onClickListener);
        BitmapUtils.loadImage(viewHolder.itemIvGoodsIcon, quoteEntity.getPic(), BitmapUtils.THE_ARTICLE);
        viewHolder.itemTvGoodsPrice.setText(quoteEntity.getPrice());
        viewHolder.itemTvGoodsAddress.setText(quoteEntity.getCity());
        viewHolder.itemTvGoodsMessage.setText(quoteEntity.getMsgX());
        if (Global.user.getUid().equals(quoteEntity.getUid())) {
            viewHolder.itemLlGoodsSupplier.setVisibility(View.GONE);
            String supplierStatus = Settings.getSharedPreferences(Settings.SUPPLIER_STATUS);
            switch (Integer.valueOf(supplierStatus)) {

                case 4:
                    viewHolder.itemLlGoodsCertification.setVisibility(View.GONE);
                    break;

                default:
                    viewHolder.itemLlGoodsCertification.setVisibility(View.VISIBLE);
                    viewHolder.itemTvCertificationImmediately.setText("<立即认证>");
                    viewHolder.itemTvCertificationImmediately.setEnabled(true);
                    break;

            }
            viewHolder.itemTvCertificationImmediately.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RedwineDetailResponse.DataEntity.PublishEntity mPublishEntity = new RedwineDetailResponse.DataEntity.PublishEntity();
                    mPublishEntity.setUid(quoteEntity.getUid());
                    Intent intent = new Intent(context, ApplyForSupplierActivity.class);
                    intent.putExtra(ApplyForSupplierActivity.PUBLISH_ENTITY, mPublishEntity);
                    context.startActivity(intent);
                }
            });
        } else {
            viewHolder.itemLlGoodsCertification.setVisibility(View.GONE);
            if (4 != quoteEntity.getSupplier_status()) {
                //供应商认证失败
                viewHolder.itemLlGoodsSupplier.setVisibility(View.VISIBLE);
            } else {
                //供应商成功
                viewHolder.itemLlGoodsSupplier.setVisibility(View.GONE);
            }
        }
        return convertView;
    }


    public static class ViewHolder {
        public View rootView;
        public ImageView itemIvUserIcon;
        public TextView itemTvUserName;
        public TextView itemTvUserPhone;
        public TextView itemTvDate;
        public TextView itemTvSendMessage;
        public TextView itemTvAccept;
        public ImageView itemIvGoodsIcon;
        public TextView itemTvGoodsPrice;
        public TextView itemTvGoodsAddress;
        public TextView itemTvGoodsMessage;
        public TextView itemTvDeleteQuoted;
        public TextView itemTvAcceptFlag;
        public LinearLayout itemLlGoodsSupplier;
        public LinearLayout itemLlGoodsCertification;
        public TextView itemTvCertificationImmediately;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.itemIvUserIcon = (ImageView) rootView.findViewById(R.id.item_iv_user_icon);
            this.itemTvUserName = (TextView) rootView.findViewById(R.id.item_tv_user_name);
            this.itemTvAcceptFlag = (TextView) rootView.findViewById(R.id.item_tv_accept_flag);
            this.itemTvUserPhone = (TextView) rootView.findViewById(R.id.item_tv_user_phone);
            this.itemTvDate = (TextView) rootView.findViewById(R.id.item_tv_date);
            this.itemTvSendMessage = (TextView) rootView.findViewById(R.id.item_tv_send_message);
            this.itemTvAccept = (TextView) rootView.findViewById(R.id.item_tv_accept);
            this.itemIvGoodsIcon = (ImageView) rootView.findViewById(R.id.item_iv_goods_icon);
            this.itemTvGoodsPrice = (TextView) rootView.findViewById(R.id.item_tv_goods_price);
            this.itemTvGoodsAddress = (TextView) rootView.findViewById(R.id.item_tv_goods_address);
            this.itemTvGoodsMessage = (TextView) rootView.findViewById(R.id.item_tv_goods_message);
            this.itemTvDeleteQuoted = (TextView) rootView.findViewById(R.id.item_tv_delete_quoted);
            this.itemLlGoodsSupplier = (LinearLayout) rootView.findViewById(R.id.item_ll_goods_supplier);
            this.itemLlGoodsCertification = (LinearLayout) rootView.findViewById(R.id.item_ll_goods_certification_hint);
            this.itemTvCertificationImmediately = (TextView) rootView.findViewById(R.id.item_tv_goods_certification_immediately);
        }

    }

    /**
     * 请求采纳
     */
    private void requestAdoptQuoteData(String publishId, String quoteUid) {
        ((ProcurementDetailActivity) context).showWaiting();
        String url = NetworkConstants.ADOPT_QUOTE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("quote_uid", quoteUid);
        params.put("publish_id", publishId);
        GsonRequest<CommonListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CommonListDataResponse.class, false, params, new Response.Listener<CommonListDataResponse>() {
            @Override
            public void onResponse(CommonListDataResponse response) {
                ((ProcurementDetailActivity) context).dismissWaiting();
                Utils.showToast(response.getMsg());
                if (response.isSuccess())
                    ((ProcurementDetailActivity) context).requestData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((ProcurementDetailActivity) context).dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 取消采纳
     */
    private void requestCancelQuoteData(String publishId, String quoteUid) {
        ((ProcurementDetailActivity) context).showWaiting();
        String url = NetworkConstants.CANCLE_QUOTE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("quote_uid", quoteUid);
        params.put("publish_id", publishId);
        GsonRequest<CommonListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CommonListDataResponse.class, false, params, new Response.Listener<CommonListDataResponse>() {
            @Override
            public void onResponse(CommonListDataResponse response) {
                ((ProcurementDetailActivity) context).dismissWaiting();
                Utils.showToast(response.getMsg());
                if (response.isSuccess())
                    ((ProcurementDetailActivity) context).requestData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((ProcurementDetailActivity) context).dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }
}
